using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using FirstTea.Domain.Entities;
using FirstTea.Domain.Repositories;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace FirstTea.Application.Services
{
    public class AuthService : IAuthService
    {
        private readonly IRepository<User> _userRepo;
        private readonly string _jwtSecret = "YourSuperSecretKey12345"; // 建议放到配置文件
        public AuthService(IRepository<User> userRepo)
        {
            _userRepo = userRepo;
        }
        public async Task<AuthResponseDto> RegisterAsync(string username, string email, string password)
        {
            var userByName = (await _userRepo.FindAsync(u => u.Username == username)).FirstOrDefault();
            if (userByName != null)
                return new AuthResponseDto { Message = "用户名已存在，请更换用户名" };
            var userByEmail = (await _userRepo.FindAsync(u => u.Email == email)).FirstOrDefault();
            if (userByEmail != null)
                return new AuthResponseDto { Message = "邮箱已注册，请更换邮箱或直接登录" };
            if (string.IsNullOrWhiteSpace(username) || username.Length < 3)
                return new AuthResponseDto { Message = "用户名长度需大于2位" };
            if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
                return new AuthResponseDto { Message = "密码长度需大于5位" };
            if (string.IsNullOrWhiteSpace(email) || !email.Contains("@"))
                return new AuthResponseDto { Message = "邮箱格式不正确" };
            var user = new User {
                Id = Guid.NewGuid(), // 自动分配 Guid 主键
                Username = username,
                Email = email,
                PasswordHash = BCrypt.Net.BCrypt.HashPassword(password)
            };
            await _userRepo.AddAsync(user);
            await _userRepo.SaveChangesAsync();
            return new AuthResponseDto { Username = user.Username, UserId = user.Id, Email = user.Email, Message = "注册成功" };
        }
        public async Task<AuthResponseDto> LoginAsync(string username, string password)
        {
            var user = (await _userRepo.FindAsync(u => u.Username == username)).FirstOrDefault();
            if (user == null || !BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
                return new AuthResponseDto { Message = "用户名或密码错误" };
            var token = GenerateJwtToken(user);
            return new AuthResponseDto { Token = token, Username = user.Username, UserId = user.Id, Email = user.Email, Message = "登录成功" };
        }
        private string GenerateJwtToken(User user)
        {
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Username ?? ""),
                new Claim(JwtRegisteredClaimNames.Email, user.Email ?? "")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: "FirstTea",
                audience: "FirstTeaUsers",
                claims: claims,
                expires: DateTime.UtcNow.AddHours(2),
                signingCredentials: creds
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
